package com.ruoyi.web.controller.api.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.druid.sql.visitor.functions.Now;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import com.egdk.api.entity.*;
import com.egdk.api.mapp.*;
import com.fasterxml.jackson.annotation.JsonRawValue;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.framework.web.domain.server.Sys;
import com.ruoyi.system.domain.TabPtdetail;
import com.ruoyi.system.domain.report.vo.*;
import com.ruoyi.system.mapper.TabPtdetailMapper;
import com.ruoyi.system.mapper.report.PatientMapper;
import com.ruoyi.web.controller.api.dto.*;
//import javafx.scene.control.Tab;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class ApiServiceImpl {


    @Autowired
    private PatientEntityMapper patientEntityMapper;

    @Autowired
    private PtdetailEntityMapper ptdetailEntityMapper;

    @Autowired
    private DICOMSeriesEntityMapper dicomSeriesEntityMapper;

    @Autowired
    private DICOMStudiesEntityMapper dicomStudiesEntityMapper;

    @Autowired
    private DICOMImagesEntityMapper dicomImagesEntityMapper;

    @Autowired
    private TabImagesNEntityMapper tabImagesNEntityMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private TabPtdetailMapper tabPtdetailMapper;

    private static final String DOWNLOAD_DCM = "DOWNLOAD_DCM_";
    private static String CHAR = "\r\n";

    public JSONObject getInfo(String accessToken) {
        String objStr = redisTemplate.opsForValue().get(accessToken);
        if (StringUtils.isNotEmpty(objStr)) {
            JSONObject object = JSONObject.parseObject(objStr);
            return object;
        }
        return null;
    }

    public String getIni(String accessToken) {
        String objStr = redisTemplate.opsForValue().get(accessToken);
        if (StringUtils.isNotEmpty(objStr)) {
            JSONObject root = JSONObject.parseObject(objStr);

            JSONObject studyObj = root.getJSONObject("Study");
            StringBuilder builder = new StringBuilder();
            builder.append("[TPatRecord]").append(CHAR);
            builder.append("Pat_PatID").append("=").append(studyObj.getString("PatientID")).append(CHAR);
            builder.append("Stu_StuDes").append("=").append(studyObj.getString("StudyDescription")).append(CHAR);
            builder.append("Pat_PatNam").append("=").append(studyObj.getString("PatientName")).append(CHAR);
            builder.append("Pat_PatSex").append("=").append(studyObj.getString("PatientSex")).append(CHAR);
            builder.append("Pat_PatBirDat").append("=").append(studyObj.getString("PatientBirthDate")).append(CHAR);
            builder.append("Stu_PatAge").append("=").append(studyObj.getString("PatientsAge")).append(CHAR);
            builder.append("Stu_StuDat").append("=").append(studyObj.getString("StudyDate")).append(CHAR);
            builder.append("Stu_StuInsUID").append("=").append(studyObj.getString("StudyInsta")).append(CHAR);
            builder.append("Stu_Priv").append("=").append("").append(CHAR);
            builder.append("Stu_PatSize").append("=").append(studyObj.getString("PatientSize")).append(CHAR);
            builder.append("Institution").append("=").append("").append(CHAR);
            builder.append("Manufacturer").append("=").append(studyObj.getString("Manufacturer")).append(CHAR);
            builder.append("ModelName").append("=").append(studyObj.getString("ModelName")).append(CHAR);
            builder.append("pat_uid").append("=").append(studyObj.getString("pat_uid")).append(CHAR);
            builder.append("pat_mid").append("=").append("").append(CHAR);
            builder.append("pat_name").append("=").append(studyObj.getString("pat_name")).append(CHAR);
            builder.append(CHAR);
            builder.append("iSerCount").append("=").append(studyObj.getString("iSerCount")).append(CHAR);
            builder.append("cBoxWindow").append("=").append(studyObj.getString("cBoxWindow")).append(CHAR);
            builder.append("Server").append("=").append("FUSION_SCREENCAP_A0662").append(CHAR);
            builder.append("ScreenForceTo").append("=").append(studyObj.getString("ScreenForceTo")).append(CHAR);
            builder.append("RegOpenMode").append("=").append("0").append(CHAR);
            builder.append(CHAR);

            JSONArray seriesArray = root.getJSONArray("Series");
            for (int i = 0; i < seriesArray.size(); i++) {
                JSONObject seriesObj = seriesArray.getJSONObject(i);
                builder.append("[" + i + "]").append(CHAR);
                builder.append("SerNum").append("=").append(seriesObj.getString("SeriesNumber")).append(CHAR);
                builder.append("Modality").append("=").append(seriesObj.getString("Modality")).append(CHAR);
                builder.append("SerDes").append("=").append(seriesObj.getString("SeriesDescription")).append(CHAR);
                builder.append("BodParExa").append("=").append(seriesObj.getString("BodyPartExamined")).append(CHAR);
                builder.append("SerInsUID").append("=").append(seriesObj.getString("SeriesInst")).append(CHAR);
                builder.append("StuParent").append("=").append(seriesObj.getString("StudyInsta")).append(CHAR);
                builder.append("Manufacturer").append("=").append(seriesObj.getString("Manufacturer")).append(CHAR);
                builder.append("ModelName").append("=").append(seriesObj.getString("ModelName")).append(CHAR);
                builder.append("RadionuclideTotalDose").append("=").append(seriesObj.getString("RadionuclideTotalDose")).append(CHAR);
                builder.append("RadionuclideStartTime").append("=").append(seriesObj.getString("RadionuclideStartTime")).append(CHAR);
                builder.append("NumSerRelIma").append("=").append(seriesObj.getString("NumSerRelIma")).append(CHAR);
                builder.append("iCount").append("=").append(seriesObj.getString("iCount")).append(CHAR);
                builder.append("iFrames").append("=").append(seriesObj.getString("NumFrames")).append(CHAR);
                JSONArray imageArray = seriesObj.getJSONArray("Images");
                for (int k = 0; k < imageArray.size(); k++) {
                    JSONObject imageObj = imageArray.getJSONObject(k);
                    builder.append(k).append("=").append(imageObj.getString("ImageNumber")).append("@").append(imageObj.getString("ImagePositionPatient")).append("@").append("C:\\nanda\\data").append(imageObj.getString("ObjectFile")).append(CHAR);
                }
                builder.append(CHAR);
            }

            return builder.toString();
        }
        return null;
    }

    @Autowired
    private MedicalCaptureMapper medicalCaptureMapper;

    @Value("${nginx.dcm-path}")
    private String dcmPath;

    @Value("${nginx.images-path}")
    private String imagesPath;

    @Value("${MAG0}")
    private String MAG0;

    @Value("${HOST_URL}")
    private String HOST;

    @Value("${CUTIMAGEPATH}")
    private String CUTIMAGEPATH;

    @Value("${IMAGEROOT}")
    private String imageRoot;


    // TODO: 2023/5/13
    public void handleImageCaptute(MedicalCapture capture) {
        //查询ptdeatilEntity
        PtdetailEntityExample ptdetailExample = new PtdetailEntityExample();
        ptdetailExample.createCriteria().andStudyinstaEqualTo(capture.getStudyinsta());
        List<PtdetailEntity> ptdetailEntities = ptdetailEntityMapper.selectByExample(ptdetailExample);

        //路径生成
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(ptdetailEntities)) {
            PtdetailEntity ptdetail = ptdetailEntities.get(0);
            StringBuilder path = new StringBuilder("/");
            String studyRecordID = String.format("%10s", ptdetail.getPtdeid()).replace(" ", "0");
            String studyCode = String.format("%10s", ptdetail.getPtdtCheckcode()).replace(" ", "0");
            path
                    .append(capture.getStudydate().substring(0, 6))
                    .append("/")
                    .append(studyRecordID)
                    .append("_")
                    .append(studyCode)
                    .append("/");
            //文件名
            String ptdtCheckcode = ptdetail.getPtdtCheckcode();
            String fileName = ptdtCheckcode + "_" + UUID.randomUUID().toString().replace("-", "");
            String picLast = capture.getPicfile().substring(capture.getPicfile().lastIndexOf('.'), capture.getPicfile().length());
            String dcmLast = capture.getDcmfile().substring(capture.getDcmfile().lastIndexOf('.'), capture.getDcmfile().length());

            //存储过程
            byte[] picBytes = castBase64StrToBytes(capture.getPicstr());
            if (picBytes != null) {
                try {
                    FileUtils.writeByteArrayToFile(new File(CUTIMAGEPATH + imageRoot + path + fileName + picLast), picBytes);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            byte[] dcmBytes = castBase64StrToBytes(capture.getDcmstr());
            if (dcmBytes != null) {
                try {
                    FileUtils.writeByteArrayToFile(new File(CUTIMAGEPATH + imageRoot + path + fileName + dcmLast), dcmBytes);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            LocalDateTime now = LocalDateTime.now();
            String date = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            String time = now.format(DateTimeFormatter.ofPattern("HHmmss"));

            TabImagesNEntityWithBLOBs tabImagesNEntityWithBLOBs = new TabImagesNEntityWithBLOBs();
            tabImagesNEntityWithBLOBs.setImPtdtid(Long.valueOf(ptdetail.getPtdeid()));
            tabImagesNEntityWithBLOBs.setImImname(capture.getPicfile());//初始可以就用上传的本来的文件名一致即可
            tabImagesNEntityWithBLOBs.setImSsserial(5);//分组，固定为5
            tabImagesNEntityWithBLOBs.setSequence(2);//序列号，固定为2
            tabImagesNEntityWithBLOBs.setImagedate(date);
            tabImagesNEntityWithBLOBs.setImagetime(time);
            tabImagesNEntityWithBLOBs.setImageGroup("01");
            tabImagesNEntityWithBLOBs.setImauid(capture.getStudyinsta());
            tabImagesNEntityWithBLOBs.setImagePath(path.toString());
            tabImagesNEntityWithBLOBs.setImageName(fileName);
            tabImagesNEntityWithBLOBs.setImageRoot(imageRoot);
            tabImagesNEntityWithBLOBs.setImagedescription(capture.getImadesc());
            tabImagesNEntityWithBLOBs.setImageFormat(capture.getFormat());
            tabImagesNEntityWithBLOBs.setStudyinsta(capture.getStudyinsta());


            tabImagesNEntityMapper.insertSelective(tabImagesNEntityWithBLOBs);
        } else {
            try {
                throw new Exception("无病人数据");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    }

    private byte[] castBase64StrToBytes(String base64Str) {
        if (StringUtils.isEmpty(base64Str)) {
            return null;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] bytes = decoder.decodeBuffer(base64Str);
            return bytes;
        } catch (IOException e) {
            return null;
        }
    }

    public void series(SeriesVo seriesVo) {
        JSONObject object = new JSONObject();

        object.put("function", seriesVo.getFunction());
        object.put("action", seriesVo.getAction());

        //根据SeriesInsta查询Study
        //通过seriesVo的第一个序列的检查ID查询study
        List<DICOMStudiesEntity> studies = dicomStudiesEntityMapper.selectByStudyInsta(seriesVo.getSeries().get(0).getStudyInsta());

        DICOMStudiesEntity studiesEntity = studies.get(0);
        //根据studyInsta查询Ptdetail
        PtdetailEntityExample ptdetailExample = new PtdetailEntityExample();
        ptdetailExample.createCriteria().andStudyinstaEqualTo(studiesEntity.getStudyinsta());
        List<PtdetailEntity> ptdetailEntities = ptdetailEntityMapper.selectByExample(ptdetailExample);

        //装载Study数据
        JSONObject studyObj = new JSONObject();
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(ptdetailEntities)) {
            PtdetailEntity ptdetail = ptdetailEntities.get(0);
            Integer patientId = ptdetail.getPtdtPatientid();

            //根据patientId查询PatientEntity
            PatientEntityExample patientExample = new PatientEntityExample();
            patientExample.createCriteria().andPatientidEqualTo(patientId);
            List<PatientEntity> patientEntities = patientEntityMapper.selectByExample(patientExample);
            PatientEntity patientEntity = patientEntities.get(0);

            studyObj.put("pat_mid", patientEntity.getPtMid());
            studyObj.put("pat_uid", patientEntity.getPtUid());
            studyObj.put("pat_name", patientEntity.getPtName());
        }

        studyObj.put("PatientID", studiesEntity.getPatientid());
        studyObj.put("StudyDescription", studiesEntity.getStudydescription());
        studyObj.put("PatientName", studiesEntity.getPatientname());
        studyObj.put("PatientSex", studiesEntity.getPatientsex());
        studyObj.put("PatientBirthDate", studiesEntity.getPatientbirthdate());
        studyObj.put("PatientsAge", studiesEntity.getPatientsage());
        studyObj.put("StudyDate", studiesEntity.getStudydate());
        studyObj.put("StudyInsta", studiesEntity.getStudyinsta());
        studyObj.put("PatientSize", studiesEntity.getPatientsize());
        studyObj.put("Institution", studiesEntity.getInstitutionname());
        studyObj.put("Manufacturer", studiesEntity.getManufacturer());
        studyObj.put("ModelName", studiesEntity.getModelname());
        studyObj.put("iSerCount", seriesVo.getSeries().size());
        studyObj.put("cBoxWindow", "0");
        studyObj.put("ScreenForceTo", "0");
        studyObj.put("Server", "");
        studyObj.put("Client", "");
        object.put("Study", studyObj);

        JSONArray seriesArr = new JSONArray();
        for (DICOMSeriesImgVo serie : seriesVo.getSeries()) {

            //装载Series数据
            JSONObject seriesObj = new JSONObject();

            seriesObj.put("SeriesNumber", serie.getSeriesNumber());
            seriesObj.put("Modality", serie.getModality());
            seriesObj.put("SeriesDescription", serie.getSeriesDescription());
            seriesObj.put("BodyPartExamined", serie.getBodyPartExamined());
            seriesObj.put("SeriesInst", serie.getSeriesInst());
            seriesObj.put("StudyInsta", serie.getStudyInsta());
            seriesObj.put("Manufacturer", serie.getManufacturer());
            seriesObj.put("ModelName", serie.getModelName());
            seriesObj.put("SeriesDate", serie.getSeriesDate());
            seriesObj.put("SeriesTime", serie.getSeriesTime());
            seriesObj.put("RadionuclideTotalDose", serie.getRadionuclideTotalDose());
            seriesObj.put("RadionuclideStartTime", serie.getRadionuclideStartTime());
            seriesObj.put("NumSerRelIma", serie.getNumSerRelIma());
            seriesObj.put("NumFrames", serie.getNumFrames());
            //装载图像数据
            List<DICOMImagesEntity> dicomImages = new ArrayList<>();
            if (Objects.equals(serie.getNumFrames(), serie.getNumSerRelIma())) {
                dicomImages = dicomImagesEntityMapper.selectDicomImageWhenEqual(serie.getSeriesInst());
            } else {
                dicomImages = dicomImagesEntityMapper.selectDicomImageWhenNotEqual(serie.getSeriesInst());
            }

            if (CollUtil.isNotEmpty(dicomImages)) {
                seriesObj.put("PixelSpacing", dicomImages.stream().map(DICOMImagesEntity::getPixelspacing).findFirst().get());

                Integer iCount = 0;
                JSONArray imageArr = new JSONArray();
                for (DICOMImagesEntity image : dicomImages) {
                    JSONObject imageObj = new JSONObject();
                    imageObj.put("ImageNumber", image.getImagenumber());
                    imageObj.put("ImagePositionPatient", image.getImagepositionpatient());
                    String uuid = DOWNLOAD_DCM + UUID.randomUUID().toString().replaceAll("-", "");
                    imageObj.put("Root", HOST + uuid);

                    //缓存到redis，设置缓存时间为1小时
                    imageObj.put("ObjectFile", image.getObjectfile());
                    if (image.getDevicename().equalsIgnoreCase("MAG0")) {
                        String dcmPath = MAG0 + image.getObjectfile();
                        if (FileUtil.exist(new File(dcmPath))) {
                            iCount++;
                            String objectFile = image.getObjectfile();
                            //文件名
                            String diskfilename = objectFile.substring(objectFile.lastIndexOf("\\") + 1, objectFile.length());
                            //设置文件路径,并缓存到redis，设置缓存时间为1小时
                            redisTemplate.opsForValue().set(uuid, JSONObject.toJSONString(new ImgDownDto(dcmPath, "1", diskfilename)), 1, TimeUnit.HOURS);
                        }

                    }
                    imageArr.add(imageObj);
                }
                seriesObj.put("iCount", iCount);

                seriesObj.put("Images", imageArr);
            }
            seriesArr.add(seriesObj);
        }
        object.put("Series", seriesArr);
        //设置accessToken返回数据
        redisTemplate.opsForValue().set(seriesVo.getUuid(), object.toJSONString(), 10, TimeUnit.MINUTES);
    }


    public void downloadDcm(String uuid, HttpServletResponse response) {
        String val = redisTemplate.opsForValue().get(uuid);
        if (StringUtils.isEmpty(val)) {

            response.setHeader("Etag", "W/\"9767057-1323779115364\"");
            response.addHeader("status", "invalid");
            writeOutStream(response, null);
        } else {
            ImgDownDto imgdown = JSONObject.parseObject(val, ImgDownDto.class);
            String diskfilename = imgdown.getDiskfilename();

            if ("1".equalsIgnoreCase(imgdown.getType())) {
                String path = imgdown.getPath();
                try {
                    byte[] data = IOUtils.toByteArray(new FileInputStream(new File(path)));
                    String type = new MimetypesFileTypeMap().getContentType(new File(path));

                    //设置header
                    response.setContentType(type);
                    response.setHeader("Content-Disposition", "attachment; filename=\"" + diskfilename + "\"");
                    response.setContentLength(data.length);
                    response.setHeader("Content-Range", "" + (data.length - 1));
                    response.setHeader("Accept-Ranges", "bytes");

                    writeOutStream(response, data);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    private void writeOutStream(HttpServletResponse response, byte[] bytes) {
        try {
            OutputStream os = response.getOutputStream();
            if (bytes != null) {
                os.write(bytes);
            }
            //先声明的流后关掉！
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    public AjaxResult getImage(String studyInsta) {
        TabImagesNEntityExample tabImagesNEntityExample = new TabImagesNEntityExample();
        tabImagesNEntityExample.createCriteria().andStudyinstaEqualTo(studyInsta);
        List<TabImagesNEntity> tabImagesNEntities = tabImagesNEntityMapper.selectByExample(tabImagesNEntityExample);

        ArrayList<String> imagesVos = new ArrayList<String>();
        if (ObjectUtil.isNotEmpty(tabImagesNEntities)) {
            for (TabImagesNEntity t : tabImagesNEntities) {
                String imageRoot1 = t.getImageRoot();
                String imagePath = t.getImagePath();
                String imageName = t.getImageName();
                String imageFormat = t.getImageFormat();
                String completePath = imageRoot1 + imagePath + imageName
                        + "." + imageFormat;
                imagesVos.add(completePath);
            }
            return AjaxResult.success(imagesVos);
        }

        return AjaxResult.success("没有相关路径");
    }


    public AjaxResult getImagesMap(String studyInsta) {
        TabImagesNEntityExample tabImagesNEntityExample = new TabImagesNEntityExample();
        tabImagesNEntityExample.createCriteria().andStudyinstaEqualTo(studyInsta);
        List<TabImagesNEntity> tabImagesNEntities = tabImagesNEntityMapper.selectByExample(tabImagesNEntityExample);
        Integer number = 0;
        List<StudyInstaImages> list = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(tabImagesNEntities)) {
            for (TabImagesNEntity t : tabImagesNEntities) {
                String imageRoot1 = t.getImageRoot();
                String imagePath = t.getImagePath();
                String imageName = t.getImageName();
                String imageFormat = t.getImageFormat();
                String completePath = imageRoot1 + imagePath + imageName + "." + imageFormat;
                list.add(new StudyInstaImages(completePath, ++number));
            }
            return AjaxResult.success(list);
        }
        StudyInstaImages noImage = new StudyInstaImages("没有相关路径", 0);
        return AjaxResult.success(0);

    }

    public List<GetImageDto> getImagesMap2(String im_ptdeid) {
        TabImagesNEntityExample tabImagesNEntityExample = new TabImagesNEntityExample();
        tabImagesNEntityExample.createCriteria().andStudyinstaEqualTo(im_ptdeid);
        List<TabImagesNEntity> tabImagesNEntities = tabImagesNEntityMapper.selectByExample2(im_ptdeid);
        Integer number = 0;
        List<GetImageDto> list = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(tabImagesNEntities)) {
            for (TabImagesNEntity t : tabImagesNEntities) {
                String imageRoot = t.getImageRoot();
                String imagePath = t.getImagePath();
                StringBuilder sb = new StringBuilder(imagePath);
                sb.replace(6, 7, "/");
                String imagePath2 = sb.toString();
                String imageName = t.getImageName();
                String imageFormat = t.getImageFormat();

                String completePath = "/www/wwwroot/yunjiaopei/" + imageRoot + "/" + imagePath2 + "/" + imageName;
                GetImageDto getImageDto = new GetImageDto();
                getImageDto.setImageID(t.getImageid());
                getImageDto.setImageDescription(t.getImagedescription());
                getImageDto.setImageBase64(completePath);
                list.add(getImageDto);
            }
        }
        return list;
    }

    public String getOneImage(String id) {
        TabImagesNEntityExample tabImagesNEntityExample = new TabImagesNEntityExample();
        tabImagesNEntityExample.createCriteria().andStudyinstaEqualTo(id);
        TabImagesNEntity tabImagesNEntities = tabImagesNEntityMapper.selectOneImage(id);
        String completePath = new String();
        if (ObjectUtil.isNotEmpty(tabImagesNEntities)) {
            String imageRoot = tabImagesNEntities.getImageRoot();
            String imagePath = tabImagesNEntities.getImagePath();
            StringBuilder sb = new StringBuilder(imagePath);
            sb.replace(6, 7, "/");
            String imagePath2 = sb.toString();
            completePath = "D:/IMAGES/" + imageRoot + "/" + imagePath2 + "/" + tabImagesNEntities.getImImname();
        }
        return completePath;
    }

    public String getOneImageByname(String name) {
        TabImagesNEntityExample tabImagesNEntityExample = new TabImagesNEntityExample();
        tabImagesNEntityExample.createCriteria().andStudyinstaEqualTo(name);
        TabImagesNEntity tabImagesNEntities = tabImagesNEntityMapper.selectOneImageByname(name);
        String completePath = new String();
        if (ObjectUtil.isNotEmpty(tabImagesNEntities)) {
            String imageRoot = tabImagesNEntities.getImageRoot();
            String imagePath = tabImagesNEntities.getImagePath();
            StringBuilder sb = new StringBuilder(imagePath);
            sb.replace(6, 7, "/");
            String imagePath2 = sb.toString();
            completePath = "D:/IMAGES/" + imageRoot + "/" + imagePath2 + "/" + tabImagesNEntities.getImImname();
        }
        return completePath;
    }


    public AjaxResult delImages(List<String> list) {
        String studyInsta = list.get(0);
        TabImagesNEntityExample tabImagesNEntityExample = new TabImagesNEntityExample();
        tabImagesNEntityExample.createCriteria().andStudyinstaEqualTo(studyInsta);
        List<TabImagesNEntity> tabImagesNEntities = tabImagesNEntityMapper.selectByExample(tabImagesNEntityExample);
        Integer number = 0;
        if (ObjectUtil.isNotEmpty(tabImagesNEntities)) {
            for (TabImagesNEntity t : tabImagesNEntities) {
                String imageRoot1 = t.getImageRoot();
                String imagePath = t.getImagePath();
                String imageName = t.getImageName();
                String imageFormat = t.getImageFormat();
                String completePath = imageRoot1 + imagePath + imageName + "." + imageFormat;
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).equals(completePath)) {
                        tabImagesNEntityMapper.delImages(imageRoot1, imagePath, imageName, imageFormat);
                    }
                }

            }

            return AjaxResult.success();
        }
        return AjaxResult.success("没有图片");
    }


    public AjaxResult getPatientMessage(String ptdeid) {
        GetMessageDto getMessageDto = new GetMessageDto();
        // 获取姓名
        String name = tabImagesNEntityMapper.getPatientName(ptdeid);

        // 获取检查号
        String ptdtCheckCode = tabImagesNEntityMapper.getPtdtCheckCode(ptdeid);

        // 获取日期
        String ptdtCheckDate = tabImagesNEntityMapper.getPtdtCheckData(ptdeid);
        String ptdtCheckDate2 = ptdtCheckDate.substring(0, 10);

        getMessageDto.setPtNameAndCheckCodeAndCheckData(name + " [ " + ptdtCheckCode + " " + ptdtCheckDate2 + " ]");


        Map<String, List<String>> map = new HashMap<>();
        // 获取一级列表以及其中对应的数据数量
        List<SerialnameAndCountDto> list1 = tabImagesNEntityMapper.getSerialnameAndCount(ptdeid);
        for (SerialnameAndCountDto s : list1) {
            String serialname = s.getImSerialname();
            int count1 = s.getCount1();
            String serialnameAndCount = serialname + " (" + count1 + ")";
            List<String> list2 = tabImagesNEntityMapper.getImageName(ptdeid, serialname);
            map.put(serialnameAndCount, list2);
        }
        getMessageDto.setImSerialnameAndCount1(map);
        return AjaxResult.success(getMessageDto);
    }

    // 根据图像id获取对应的图像描述
    public String getImageDescription(Long imageID) {
        return tabImagesNEntityMapper.getImageDescription(imageID);
    }

    // 保存图像对应的描述
    public void setImageDescription(SetImageDecription imageDecription) {
        tabImagesNEntityMapper.setImageDescription(imageDecription.getImageDescription(), imageDecription.getImageID());
    }

    // 删除对应图片（将bdel设置为1）
    public void deleteImage(ImageIdDto imageIDList) {
        for (Long imageID : imageIDList.getImageIdList()) {
            tabImagesNEntityMapper.deleteImage(imageID);
        }
    }

    // 将模板中的对应位置的值替换（将数据插入到表格对应位置中）
    // 输出word文档
    public List<String> insertAndOutFile(String templateFilePath, Map<String, String> map, String fileName, String folderPath, List<String> imagePathList) throws IOException, InvalidFormatException {
        //准备工作，生成docx对象
        String templatePath = templateFilePath;
        InputStream is = new FileInputStream(templatePath);
        XWPFDocument docx = new XWPFDocument(is);

        // 返回打印的对应地址列表
        List<String> result = new ArrayList<>();

        for (String path : imagePathList) {
            //获取表格
            List<XWPFTable> tables = docx.getTables();
            //定位到第一个表格
            XWPFTable table = tables.get(0);
            //遍历该表格所有的行
            for (int i = 0; i < table.getRows().size(); i++) {
                XWPFTableRow row = table.getRow(i);
                //遍历该行所有的列
                for (int j = 0; j < row.getTableCells().size(); j++) {
                    XWPFTableCell cell = row.getTableCells().get(j);
                    //获取该格子里所有的段
                    List<XWPFParagraph> paragraphs = cell.getParagraphs();
                    for (XWPFParagraph p : paragraphs) {
                        //遍历该格子里的段
                        List<XWPFRun> runs = p.getRuns();
                        for (XWPFRun run : runs) {
                            //遍历该段里的所有文本
                            String str = run.toString();
                            //如果该段文本包含map中的key，则替换为map中的value值。
                            Set<String> keySet = map.keySet();
                            for (String key : keySet) {
                                if (str.trim().equals(key)) {
                                    //替换该文本0位置的数据。
                                    run.setText(map.get(key), 0);
                                }
                            }
                        }
                    }
                }
            }

            XWPFParagraph paragraph = docx.createParagraph();
            XWPFRun run = paragraph.createRun();
            // 插入图片
            run.addPicture(new FileInputStream(path),
                    XWPFDocument.PICTURE_TYPE_PNG,
                    "1.png",
                    Units.toEMU(520),
                    Units.toEMU(560));
        }

        // 将文件保存到指定的文件夹
        try {
            // 如果路径不存在则自动创建
            String path = folderPath + "\\" + fileName;
            File file = new File(path);
            File fileParent = file.getParentFile();
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }
            file.createNewFile();

            // 输出word
            FileOutputStream out = new FileOutputStream(new File(folderPath, fileName));
            docx.write(out);
            out.close();
            String path2 = "Word文档已成功保存到： " + folderPath + "\\" + fileName;
            result.add(path2);


            // 输出pdf
            File inputWord = new File(folderPath + "\\" + fileName);
            fileName = fileName.replace("docx", "pdf");
            File outputFile = new File(folderPath + "\\" + fileName);
            try {
                InputStream docxInputStream = new FileInputStream(inputWord);
                OutputStream outputStream = new FileOutputStream(outputFile);
                IConverter converter = LocalConverter.builder().build();
                converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
                outputStream.close();
                path2 = "Pdf文档已成功保存到： " + folderPath + "\\" + fileName;
                result.add(path2);
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;

    }

    // 输出文字word文档
    public String insertAndOutFileWriting(String templateFilePath, Map<String, String> map, String fileName, String folderPath) throws IOException {
        //准备工作，生成docx对象
        String templatePath = templateFilePath;
        InputStream is = new FileInputStream(templatePath);
        XWPFDocument docx = new XWPFDocument(is);

        // 返回文件路径
        String path1 = "";

        //获取表格
        List<XWPFTable> tables = docx.getTables();
        //定位到第一个表格
        XWPFTable table = tables.get(0);
        //遍历该表格所有的行
        for (int i = 0; i < table.getRows().size(); i++) {
            XWPFTableRow row = table.getRow(i);
            //遍历该行所有的列
            for (int j = 0; j < row.getTableCells().size(); j++) {
                XWPFTableCell cell = row.getTableCells().get(j);
                //获取该格子里所有的段
                List<XWPFParagraph> paragraphs = cell.getParagraphs();
                for (XWPFParagraph p : paragraphs) {
                    //遍历该格子里的段
                    List<XWPFRun> runs = p.getRuns();
                    for (XWPFRun run : runs) {
                        //遍历该段里的所有文本
                        String str = run.toString();
                        //如果该段文本包含map中的key，则替换为map中的value值。
                        Set<String> keySet = map.keySet();
                        for (String key : keySet) {
                            if (str.trim().equals(key)) {
                                //替换该文本0位置的数据。
                                run.setText(map.get(key), 0);
                            }
                        }
                    }
                }
            }
        }


        // 将文件保存到指定的文件夹
        try {
            // 如果路径不存在则自动创建
            String path = folderPath + "\\" + fileName;
            File file = new File(path);
            File fileParent = file.getParentFile();
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }
            file.createNewFile();

            // 输出word
            FileOutputStream out = new FileOutputStream(new File(folderPath, fileName));
            docx.write(out);
            out.close();


            try {
                // 读取Word文档
                FileInputStream fis = new FileInputStream(folderPath + "\\" + fileName);
                XWPFDocument document = new XWPFDocument(fis);

                // 遍历文档中的段落
                List<XWPFParagraph> paragraphs = document.getParagraphs();
                for (XWPFParagraph paragraph : paragraphs) {
                    // 遍历段落中的文本块
                    List<XWPFRun> runs = paragraph.getRuns();
                    for (XWPFRun run : runs) {
                        String text = run.getText(0);
                        if (text != null && text.contains("ptdeid")) {
                            // 替换文本
                            text = text.replace("ptdeid", map.get("ptdeid"));
                            run.setText(text, 0);
                        }
                    }
                }

                // 保存更改后的文档
                FileOutputStream fos = new FileOutputStream(folderPath + "\\" + fileName);
                document.write(fos);

                // 关闭资源
                fos.close();
                document.close();
                fis.close();

                path1 = "Word文档已成功保存到： " + folderPath + "\\" + fileName;
            } catch (IOException e) {
                e.printStackTrace();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return path1;
    }

    // 根据报告id获取对应患者的姓名、年龄、性别、检查日期、检查号
    public GetWordMessageDto getWordMessage(String ptdeid) {
        GetWordMessageDto getWordMessageDto = tabImagesNEntityMapper.getWordMessage(ptdeid);
        return getWordMessageDto;
    }


    // 上传图片
    public AjaxResult uploadImage(String base64Data, String ptdeid, String opid) {
        // 根据ptdeid获取检查日期、记录ID，检查号
        TabPtdetail tabPtdetail = tabPtdetailMapper.selectTabPtdetailByPtdeid(Long.valueOf(ptdeid));
        // 检查号前补0至10位
        tabPtdetail.setPtdtCheckcode(String.format("%010d", tabPtdetail.getPtdtCheckcode()));
        // ptdeid前补0至10位
        tabPtdetail.setPtdeid(Long.valueOf(String.format("%010d", tabPtdetail.getPtdeid())));
        // 截取检查日期保留到月份，如2022105
        String imagePathDate = tabPtdetail.getPtdtCheckdate().toString();
        String imagePath = imagePathDate.substring(0, 4) + imagePathDate.substring(5, 7) + "/" + tabPtdetail.getPtdeid() + "_" + tabPtdetail.getPtdtCheckcode();
        // 获取当前时间
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyMMdd");
        String ImageDate = formatter.format(date);
        SimpleDateFormat formatter2 = new SimpleDateFormat("HHmmss");
        String ImageTime = formatter2.format(date);
        // 设置image_root（文件存储根路径）、im_serialname（分组名）
        String image_root = "DISK0";
        String im_serialname = "序列1";

        TabImagesNEntity tabImagesNEntity = new TabImagesNEntity();
        tabImagesNEntity.setImPtdtid(tabPtdetail.getPtdeid());
        tabImagesNEntity.setImagePath(imagePath);
        tabImagesNEntity.setImagedate(ImageDate);
        tabImagesNEntity.setImagetime(ImageTime);

        tabImagesNEntity.setImageRoot("DISK0");
        tabImagesNEntity.setImSerialname("序列1");

        // 查询得到表中的数据个数
        int imageID = tabImagesNEntityMapper.selectCount() + 1;

        //base64格式前头
        String dataPrix = "";
        //实体部分数据
        String data = "";
        if (base64Data == null || "".equals(base64Data)) {
            return AjaxResult.error("上传失败，上传图片数据为空");
        } else {
            //将字符串分成数组
            String[] d = base64Data.split("base64,");
            dataPrix = d[0];
            data = d[1];
        }
        String suffix = "";
        //编码的jpeg图片数据
        if ("data:image/jpeg;".equalsIgnoreCase(dataPrix)) {
            suffix = ".jpg";
        } else if ("data:image/x-icon;".equalsIgnoreCase(dataPrix)) {
            //编码的icon图片数据
            suffix = ".ico";
        } else if ("data:image/gif;".equalsIgnoreCase(dataPrix)) {
            //编码的gif图片数据
            suffix = ".gif";
        } else if ("data:image/png;".equalsIgnoreCase(dataPrix)) {
            //编码的png图片数据
            suffix = ".png";
        } else {
            return AjaxResult.error("上传图片格式不合法");
        }
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String tempFileName = tabImagesNEntityMapper.selectptdtCheckCode(ptdeid) + "_" + uuid + suffix;
        String imgFilePath = "D:\\IMAGES\\" + image_root + "\\" + imagePath + "\\" + tempFileName;
        try {
            //Base64解码
            byte[] base64decodedBytes = Base64.getDecoder().decode(data);
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(base64decodedBytes);
            out.flush();
            out.close();
            tabImagesNEntityMapper.insertImage(imageID, ptdeid, tempFileName, im_serialname, ImageDate, ImageTime, imagePath, tempFileName, suffix, image_root, new Date());
        } catch (Exception e) {
            System.out.println(e);
            return AjaxResult.error("上传图片失败");
        }
        return AjaxResult.success();
    }


    public AjaxResult uploadImage2(MultipartFile file, String ptdeid, String opid) {
        // 根据ptdeid获取检查日期、记录ID，检查号
        TabPtdetail tabPtdetail = tabPtdetailMapper.selectTabPtdetailByPtdeid(Long.valueOf(ptdeid));
        // 检查号前补0至10位
        tabPtdetail.setPtdtCheckcode(String.format("%010d", tabPtdetail.getPtdtCheckcode()));
        // ptdeid前补0至10位
        tabPtdetail.setPtdeid(Long.valueOf(String.format("%010d", tabPtdetail.getPtdeid())));
        // 截取检查日期保留到月份，如2022105
        String imagePathDate = tabPtdetail.getPtdtCheckdate().toString();
        String imagePath = imagePathDate.substring(0, 4) + imagePathDate.substring(5, 7) + "/" + tabPtdetail.getPtdeid() + "_" + tabPtdetail.getPtdtCheckcode();
        // 获取当前时间
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyMMdd");
        String ImageDate = formatter.format(date);
        SimpleDateFormat formatter2 = new SimpleDateFormat("HHmmss");
        String ImageTime = formatter2.format(date);
        // 设置image_root（文件存储根路径）、im_serialname（分组名）
        String image_root = "DISK0";
        String im_serialname = "序列1";

        TabImagesNEntity tabImagesNEntity = new TabImagesNEntity();
        tabImagesNEntity.setImPtdtid(tabPtdetail.getPtdeid());
        tabImagesNEntity.setImagePath(imagePath);
        tabImagesNEntity.setImagedate(ImageDate);
        tabImagesNEntity.setImagetime(ImageTime);

        tabImagesNEntity.setImageRoot("DISK0");
        tabImagesNEntity.setImSerialname("序列1");

        // 查询得到表中的数据个数
        int imageID = tabImagesNEntityMapper.selectCount() + 1;

        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1, file.getOriginalFilename().length());
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String tempFileName = tabImagesNEntityMapper.selectptdtCheckCode(ptdeid) + "_" + uuid + suffix;
        String imgFilePath = "D:\\IMAGES\\" + image_root + "\\" + imagePath + "\\" + tempFileName;

        // 转存图片
        AjaxResult ajaxResult = uploadImage(file, imgFilePath, tempFileName);
        // 数据库中插入数据
        tabImagesNEntityMapper.insertImage(imageID, ptdeid, tempFileName, im_serialname, ImageDate, ImageTime, imagePath, tempFileName, suffix, image_root, new Date());

        return AjaxResult.success("上传成功", ajaxResult);
    }

    //上传操作
    private AjaxResult uploadImage(MultipartFile file, String folder, String filename) {
        if (file == null) {
            return AjaxResult.error("请选择要上传的图片");
        }
        if (file.getSize() > 1024 * 1024 * 10) {
            return AjaxResult.error("文件大小不能大于10M");
        }
        //获取文件后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1, file.getOriginalFilename().length());
        if (!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())) {
            return AjaxResult.error("请选择jpg,jpeg,gif,png格式的图片");
        }
        String savePath = folder;
        File savePathFile = new File(savePath);
        if (!savePathFile.exists()) {
            //若不存在该目录，则创建目录
            savePathFile.mkdir();
        }
        try {
            //将文件保存指定目录
            //file.transferTo(new File(savePath + filename));
            //File file1 = new File(file.getOriginalFilename());
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File(savePath + filename));
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("保存文件异常");
        }
        //返回文件名称
        return AjaxResult.success(filename, 1);
    }

    // 根据报告id获取检查日期
    public String getPtdtCheckDate(String ptdeid) {
        return tabImagesNEntityMapper.getPtdtCheckData(ptdeid);
    }

    // 获取随访的标签以及随访结果
    public ExamSurveyDto getFollow(String ptdeid) {
        return tabImagesNEntityMapper.getFollow(ptdeid);
    }

    // 保存随访结果
    public AjaxResult updateFollow(ExamSurveyDto examSurveyDto) {
        tabImagesNEntityMapper.updateFollow(examSurveyDto.getSurPtdeid(), examSurveyDto.getFollowTag(), examSurveyDto.getFollowResult());
        ExamSurveyDto examSurveyDto1 = tabImagesNEntityMapper.getFollow(examSurveyDto.getSurPtdeid());
        return AjaxResult.success("保存成功！", examSurveyDto1);
    }

    // 数据库中不存在，插入一条数据
    public AjaxResult insertFollow(ExamSurveyDto examSurveyDto) {

        // 获取对应的patientid
        String patientId = tabImagesNEntityMapper.getPatientId(examSurveyDto.getSurPtdeid());
        tabImagesNEntityMapper.insertFollow(patientId, examSurveyDto.getSurPtdeid(), examSurveyDto.getFollowTag(), examSurveyDto.getFollowResult());
        return AjaxResult.success( "插入成功", tabImagesNEntityMapper.getFollow(examSurveyDto.getSurPtdeid()));
    }

    // 获取问诊数据
    public WzDataDto getwzdata(String ptdeid) {
        return tabImagesNEntityMapper.getwzdata(ptdeid);
    }

    // 保存问诊数据
    public String updatewzdata(WzDataDto wzDataDto) {
        tabImagesNEntityMapper.updatewzdata(wzDataDto.getPtdeid(), wzDataDto.getPtdtBgproreadyTxt(), wzDataDto.getPtdtLcdiagnousTxt());
        return "保存成功！";
    }

    public AjaxResult upload(MultipartFile file, String ptdeid) {


        // 根据ptdeid获取检查日期、记录ID，检查号
        TabPtdetailDto tabPtdetailDto = tabImagesNEntityMapper.selectTabPtdetailDtoByPtdeid(ptdeid);
        // 检查号前补0至10位
        tabPtdetailDto.setPtdtCheckCode(String.format("%10s", tabPtdetailDto.getPtdtCheckCode()).replace(' ', '0'));
        // ptdeid前补0至10位
        tabPtdetailDto.setPtdeid(String.format("%10s", tabPtdetailDto.getPtdeid()).replace(' ', '0'));
        // 截取检查日期保留到月份，如2022105
        String imagePathDate = tabPtdetailDto.getPtdtCheckDate().toString();
        String imagePath1 = imagePathDate.substring(0, 4) + imagePathDate.substring(5, 7);
        String imagePath2 = tabPtdetailDto.getPtdeid() + "_" + tabPtdetailDto.getPtdtCheckCode();
        // 获取当前时间
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String ImageDate = formatter.format(date);
        SimpleDateFormat formatter2 = new SimpleDateFormat("HHmmss");
        String ImageTime = formatter2.format(date);
        // 设置image_root（文件存储根路径）、im_serialname（分组名）
        String image_root = "DISK0";
        String im_serialname = "序列1";

        TabImagesNEntity tabImagesNEntity = new TabImagesNEntity();
        tabImagesNEntity.setImPtdtid(Long.valueOf(tabPtdetailDto.getPtdeid()));
        tabImagesNEntity.setImagePath(imagePath1 + "/" + imagePath2);
        tabImagesNEntity.setImagedate(ImageDate);
        tabImagesNEntity.setImagetime(ImageTime);

        tabImagesNEntity.setImageRoot("DISK0");
        tabImagesNEntity.setImSerialname("序列1");

        // 查询得到表中的数据个数
        int imageID = tabImagesNEntityMapper.selectCount() + 1;

        String suffix = "." + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1, file.getOriginalFilename().length());
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String tempFileName = tabPtdetailDto.getPtdtCheckCode() + "_" + uuid + suffix;
        String imgFilePath = "D:/IMAGES/" + image_root + "/" + imagePath1 + "/" + imagePath2 + "/";
        String imgFilePath2 = "D:/IMAGES/" + image_root + "/" + imagePath1;

        // 转存图片
        AjaxResult ajaxResult = uploadImage(file, imgFilePath, tempFileName);
        // 数据库中插入数据
        tabImagesNEntityMapper.insertImage(imageID, ptdeid, tempFileName, im_serialname, ImageDate, ImageTime, imagePath1 + "\\" + imagePath2, tempFileName, suffix.replace(".", ""), image_root, new Date());

        //创建一个目录对象
        File dir = new File(imgFilePath2);
        //判断当前目录是否存在
        if (!dir.exists()) {
            //目录不存在，需要创建
            dir.mkdirs();
        }

        try {
            //将临时文件转存到指定位置
            file.transferTo(new File(imgFilePath + tempFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxResult.success(imgFilePath + tempFileName);
    }


    public CheckMachineDto getCheckMachineList() {
        List<String> checkMachineList = patientEntityMapper.getCheckMachineList();
        return new CheckMachineDto(checkMachineList,checkMachineList.size());
    }
}
